package io.nutz.nutzsite.module.exam.controller;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.utils.DateUtils;
import io.nutz.nutzsite.common.utils.excel.ExportExcel;
import io.nutz.nutzsite.module.exam.models.*;
import io.nutz.nutzsite.module.exam.services.*;
import io.nutz.nutzsite.module.sys.models.User;
import io.nutz.nutzsite.module.sys.services.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.plugins.slog.annotation.Slog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 成绩与试卷 信息操作处理
 * 
 * @author lrw
 * @date 2020-04-08
 */
@IocBean
@At("/exam/scores2")
public class Scores2Controller {
	private static final Log log = Logs.get();

	@Inject
	private Scores2Service scoresService;
	@Inject
	private VscoresService vscoresService;
	@Inject
	private PaperdefService paperdefService;
	@Inject
	private QuestionService questionService;
	@Inject
	private UserService userService;
	
	@RequiresPermissions("exam:scores:view")
	@At("")
	@Ok("th:/exam/scores/paperdef.html")
	public void index(HttpServletRequest req) {

	}

	//@RequiresPermissions("exam:scores:view")
	@At("/lookscore/?")
	@Ok("th:/exam/scores/scores.html")
	public void lookscore(String id,HttpServletRequest req) {
		Paperdef paperdef=paperdefService.fetch(id);		
		req.setAttribute("paperdef", paperdef);
	}
	/**
	 * 查询成绩与试卷列表
	 */
	@RequiresPermissions("exam:scores:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("uid") String uid,
					   @Param("ksid") String ksid,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(uid)){
			cnd.and("uid", "like", "%" + uid +"%");
		}
		cnd.and("ksid", "=", ksid);
		return scoresService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}

	/**
	 * 新增成绩与试卷
	 */
	@At("/add")
	@Ok("th:/exam/scores/add.html")
	public void add( HttpServletRequest req) {

	}

	/**
	 * 新增保存成绩与试卷
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("exam:scores:add")
	@Slog(tag="成绩与试卷", after="新增保存成绩与试卷 id=${args[0].id}")
	public Object addDo(@Param("..") Scores2 scores,HttpServletRequest req) {
		try {
			scoresService.insert(scores);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改成绩与试卷
	 */
	@At("/edit/?")
	@Ok("th:/exam/scores/edit.html")
	public void edit(String id, HttpServletRequest req) {
		Scores2 scores = scoresService.fetch(id);
		req.setAttribute("scores",scores);
	}

    /**
     * 详情成绩与试卷
     */
    @At("/detail/?")
    @Ok("th:/exam/scores/detail.html")
    public void detail(Integer id, HttpServletRequest req) {
		Scores2 scores = scoresService.fetch(id);
		String paperdata=scores.getPaperdata();
		req.setAttribute("now0", DateUtils.getDateTime());
		User user=userService.getField("^(id|userName|deptId|classg)$", scores.getUid());
		Paper paper=Json.fromJson(Paper.class,paperdata);
		
		NutMap qtidmap=paper.getQtidmap();
		NutMap qtidmap2=new NutMap();

		for(String key : qtidmap.keySet()){
			NutMap map=(NutMap)qtidmap.get(key);
			//NutMap idscoremap=(NutMap)map.get("idscore");
			//======================================================
			String qids=map.getString("qids");
			String[] qscores=map.getString("qscores").split(",");
			String[] stuans=map.getString("stuans").split(",");
			String[] stuscore=map.getString("stuscore").split(",");
			List<Question> qlist=questionService.query("^(id|qtid|name|ansA|ansB|ansC|ansD|qans)$",Cnd.where("id","in",qids).asc("instr(',"+qids+",',concat(',',id,','))"));
			int i=0;
			for(Question question:qlist){
				question.setQscore(Float.parseFloat( qscores[i]));
				question.setStuscore(Float.parseFloat( stuscore[i]));
				if(stuans[i].equals("-")) question.setStuans("");
				else question.setStuans(stuans[i]);
				i++;
			}
			NutMap map2=new NutMap();
			map2.addv("qlist", qlist);
			map2.addv("qname", map.getString("qname"));
			map2.addv("qscore", map.getString("qscore"));
			map2.addv("score", map.getAs("score", Float.class));
			qtidmap2.addv(key, map2);
		}
		qtidmap.clear();
		paper.setQtidmap(null);
		paper.setQtidmap(qtidmap2);
		
		req.setAttribute("paper", paper);
		req.setAttribute("user", user);
	}

    /**
	 * 修改保存成绩与试卷
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("exam:scores:edit")
	@Slog(tag="成绩与试卷", after="修改保存成绩与试卷")
	public Object editDo(@Param("..") Scores scores,HttpServletRequest req) {
		try {
			if(Lang.isNotEmpty(scores)){

				scoresService.update(scores);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 删除成绩与试卷
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("exam:scores:remove")
	@Slog(tag ="成绩与试卷", after= "删除成绩与试卷:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			scoresService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
    @At
	@Ok("json")
    public Object export(@Param("ksid") String ksid,
			   HttpServletRequest req, HttpServletResponse response) {
    	Cnd cnd = Cnd.NEW();
		if(ksid!=null){
			cnd.and("ksid","=", ksid);
		}
    	List<Vscores> list = vscoresService.query(cnd);
    	
    	Paperdef paperdef=paperdefService.fetch(ksid);
    	String tname=paperdef.getName()+"_成绩数据";
		String fileName = tname + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try{
			new ExportExcel(tname, Vscores.class).setDataList(list).writeFile(fileName);
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("导出失败"+ex.getMessage());
		}
		return Result.success(fileName);
    }
}
